<?php

/**
 * Wpay.
 */

namespace app\api\service\payment;

use app\api\service\ApiPayment;
use app\common\library\exception\OrderException;
use app\api\service\payment\F4stpay\Client as F4stpayClient;

class Wpay extends ApiPayment
{
    public function alipay($order)
    {
        return $this->requestApi($order);
    }

    public function upmp($order)
    {
        return $this->requestApi($order, 'alipay');
    }

    public function wxpay($order)
    {
        return $this->requestApi($order, 'wxpay');
    }

    public function jdpay($order)
    {
        return $this->requestApi($order, 'jdpay');
    }

    public function ysf($order)
    {
        return $this->requestApi($order, 'ysf');
    }

    function send_post($url, $params)
    {
        $postdata = http_build_query($params);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    public function requestApi($order, $type = 'alipay')
    {
        $params = array(
            "app_id" => $this->config['app_id'], //微派分配的appId,联系运营人员获取，实际项目中请替换真实appId
            "body" => $order['subject'], //商品名称，必填项，请勿包含敏感词
            "callback_url" => "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/success", //支付成功后跳转的界面
            "notify_url" => "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/notify/wpay",
            "channel_id" => "appStore", //渠道编号,自定义
            "format" => "json", //返回数据格式，填写固定值 json
            "out_trade_no" => $order['trade_no'], //商户单号，确保不重复，必填项
            "pay_type" => $type, //支付方式，必填项
            "total_fee" => $order['amount'], //商品价格(单位:��)，必填项
            "version" => "3.0", //版本号，默认填写3.0即可，必填项
        );
        $params = array_filter($params); //去除空值，空值不参与签名
        ksort($params); //按字母序
        $paramStr = implode('&', array_map(
            function ($v, $k) {
                return sprintf("%s=%s", $k, $v);
            },
            $params,
            array_keys($params)
        ));

        //签名所需密钥(API_KEY)，注意妥善保存,勿向他人透露
        // $api_key = "CRCBwJce5ku88n8LSEbRWTg5dWAkJBiq";
        $preSign = $paramStr . $this->config['app_key'];
        $sign = strtoupper(md5($preSign));
        $params["sign"] = $sign;

        $resultStr = $this->send_post("http://up.wiipay.cn/1/jspay/api/pay.do", $params);
        $resultObj = json_decode($resultStr);
        //print_r($resp_json_str);
        if (isset($resultObj->resultCode) && (strcasecmp($resultObj->resultCode, 'success') == 0) && ($resultObj->url != '')) {
            $fileUrl = $this->makeQRimg($resultObj->url);
            return [
                    'order_id' => $order['out_trade_no'],
                    'pay_seq' => $order['trade_no'],
                    'pay_url' => $fileUrl,
                    'pay_app_url' => $fileUrl
            ];
        }

        if ((strcasecmp($resultObj->ret_state, 'success') == 0) && ($resultObj->pay_url != '')) {
            $fileUrl = $this->makeQRimg($resultObj->pay_url);
            return [
                    'order_id' => $order['out_trade_no'],
                    'pay_seq' => $order['trade_no'],
                    'pay_url' => $fileUrl,
                    'pay_app_url' => $fileUrl
            ];
        } 

        throw new OrderException([
            'msg' => $resultObj->resultMsg,
            'errCode' => 555,
        ]);
    }

    public function makeQRimg($url)
    {
        $fileName = date('Ymd').DS.date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).'.png';
        if (!file_exists(UPLOAD_PATH.'qr')) {
            mkdir(UPLOAD_PATH.'qr', 0777, true);
        }

        if (!file_exists(UPLOAD_PATH.'qr'.DS.date('Ymd'))) {
            mkdir(UPLOAD_PATH.'qr'.DS.date('Ymd'), 0777, true);
        }

        $renderer = new \BaconQrCode\Renderer\Image\Png();
        $renderer->setHeight(256);
        $renderer->setWidth(256);
        $writer = new \BaconQrCode\Writer($renderer);
        $writer->writeFile($url, UPLOAD_PATH.DS.'qr/'.$fileName);

        return UPLOAD_URL.'qr/'.$fileName;
    }


    public function notify()
    {
        return $this->verifyOrderNotify();
    }

    /**
     * 回调验签.
     *
     *
     * @return array
     *
     * @throws OrderException
     */
    private function verifyOrderNotify()
    {
        $xml = file_get_contents('php://input');
        file_put_contents("/tmp/Wpay.log", var_export($_POST, true), FILE_APPEND);
        file_put_contents("/tmp/Wpay_get.log", var_export($_GET, true), FILE_APPEND);
        file_put_contents("/tmp/Wpay_input.log", $xml, FILE_APPEND);

        if ($_REQUEST['status'] == "success") {
            return array(
                'trade_no' => $_REQUEST['cpparam'],
            );
        }

        return false;

        $xml = file_get_contents('php://input');
        libxml_disable_entity_loader(true);
        //Object  对象
        $response = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
        //读订单对应的支付渠道配置
        $this->config = self::getOrderPayConfig($response['out_trade_no']);
        $req = new Request($this->config);
        $result = $req->callback();
        if ($result) {
            return array(
                'trade_no' => $result['mercOrderId'],
            );
        }

        return false;
    }
}
